/*************************************************************************
	> File Name: config_file.c
	> Author: 
	> Mail: 
	> Created Time: 2018年09月04日 星期二 10时25分59秒
 ************************************************************************/

#include <config_file.h>

//写入配置信息
int write_config_data(config *con)
{
	//printf("max_tem=%f\tmax_hum=%f\tmax_lux=%f\n", con->max_env.tem, con->max_env.hum, con->max_env.lux);
	//printf("min_tem=%f\tmin_hum=%f\tmin_lux=%f\n", con->min_env.tem, con->min_env.hum, con->min_env.lux);
	char buf[24] = {'\0'};
	
	//以写入方式打开文件
	FILE *config = fopen(CONFIG_DATA, "w");
	
	fputs(data_char(buf, "max_tem", con->max_env.tem), config);
	fputs(data_char(buf, "max_hum", con->max_env.hum), config);
	fputs(data_char(buf, "max_lux", con->max_env.lux), config);
	
	fputs(data_char(buf, "min_tem", con->min_env.tem), config);
	fputs(data_char(buf, "min_hum", con->min_env.hum), config);
	fputs(data_char(buf, "min_lux", con->min_env.lux), config);
	fclose(config);
	printf("xie ru pei zhi wen jian cheng gong\n");
	return 0;
}

//读取配置信息
int read_config_data(config *con)
{
	int i = 0;
	//以读取方式打开文件
	memset(con, 0, sizeof(config));
	char buf[24] = {'\0'};
	FILE *con_fig = fopen(CONFIG_DATA, "r");
	config_c_d c;
	while(i < 6)
	{
		memset(buf, 0, 24);
		fgets(buf, 23, con_fig);

		char_data(buf, &c);
		//printf("buf=%s\tf=%f\n", c.buf, c.f);
		if (0 == memcmp(c.buf, "max_tem", 7))
		{
			con->max_env.tem = c.f;
		}
		else if (0 == memcmp(c.buf, "max_hum", 7))
		{
			con->max_env.hum = c.f;
		}
		else if (0 == memcmp(c.buf, "max_lux", 7))
		{
			con->max_env.lux = c.f;
		}
		else if (0 == memcmp(c.buf, "min_tem", 7))
		{
			con->min_env.tem = c.f;
		}
		else if (0 == memcmp(c.buf, "min_hum", 7))
		{
			con->min_env.hum = c.f;
		}
		else if (0 == memcmp(c.buf, "min_lux", 7))
		{
			con->min_env.lux = c.f;
		}
		i++;
	}
	//printf("max_tem=%f\tmax_hum=%f\tmax_lux=%f\n", con->max_env.tem, con->max_env.hum, con->max_env.lux);
	//printf("min_tem=%f\tmin_hum=%f\tmin_lux=%f\n", con->min_env.tem, con->min_env.hum, con->min_env.lux);
	printf("du qu pei zhi wen jian cheng gong\n");
	fclose(con_fig);
	return OK;
}

//数据拼写
char *data_char(char *buf, char *str, float f)
{
	char s[20] = {'\0'};
	memset(buf, 0, 24);
	
	memcpy(buf, str, strlen(str));
	memcpy(buf + strlen(str), "=", strlen("="));
	memcpy(buf + strlen(str) + strlen("="), gcvt(f, 8, s), strlen(gcvt(f, 8, s)));
	memcpy(buf + strlen(str) + strlen("=") + strlen(gcvt(f, 8, s)), "\n", 1);
	return buf;
}

//数据解析
int char_data(char *str, config_c_d *c)
{	
	memset(c, 0, sizeof(config_c_d));
	memcpy(c->buf, str, 7);
	c->f = atof(str + 8);	
	
	return 0;
}



























